#include<iostream>
#include<unistd.h>
#include<string.h>
#include<cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define NUM 1024

void writer(int pipfd)
{
    char buffer[NUM];
    string s = "hello, this is a child programme!";
    int cnt = 0;
    pid_t id = getpid();
    while(true)
    {
        buffer[0] = 0; //这里是字符串，每次都重新写入
        snprintf(buffer, sizeof(buffer), "%s pid = %d - %d", s.c_str(), id, cnt++); //将显示器输出到buffer数组中
        write(pipfd, buffer, strlen(buffer)); //此处无需+1，因为文件中不适用c语言字符串的规则
        sleep(1);
    }
}

void reader(int pipfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0] = 0;
        read(pipfd, buffer, sizeof(buffer));
        cout << "Father(" << getpid() << ") receives a message: " << buffer << endl;
        sleep(1);
    }

}

int main()
{
    int pipfd[2] = {0};
    int ret = pipe(pipfd); //创建管道，pidfd[0]为读。pidfd[1]为写
    if(ret < 0) return 1;

    pid_t id = fork();
    if(id < 0) return 2;
    if(id == 0)
    {
        //child
        close(pipfd[0]); //关闭读通道
        // to do list
        writer(pipfd[1]); //进行写操作

        close(pipfd[1]); //关闭文件
        exit(0); //结束子进程
    }
    //father
    close(pipfd[1]); //关闭写通道
    //to do list
    reader(pipfd[0]); //进行读操作

    close(pipfd[0]); //关闭文件
    int wait_pid = waitpid(id, nullptr, 0); //等待子进程
    if(wait_pid < 0) return 3;

    return 0;
}